package cn.huoyingkeji.system.service.impl;

import cn.huoyingkeji.system.dto.RoleDTO;
import cn.huoyingkeji.system.entity.SysRole;
import cn.huoyingkeji.system.entity.SysRoleResourceRelation;
import cn.huoyingkeji.system.mapper.SysRoleMapper;
import cn.huoyingkeji.system.mapper.SysRoleResouceRelationMapper;
import cn.huoyingkeji.system.service.RoleService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import cn.huoyingkeji.mybitisplus.service.impl.MybatisplusServiceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SysRoleServiceServiceImpl extends MybatisplusServiceImpl<SysRoleMapper, SysRole, RoleDTO> implements RoleService{


    @Resource
    private SysRoleResouceRelationMapper sysRoleResouceRelationMapper;


    @Override
    public RoleDTO toDTO(SysRole org) {
        RoleDTO orgDTO = new RoleDTO();
        BeanUtil.copyProperties(org, orgDTO, false);
        return orgDTO;
    }

    @Override
    public SysRole toEntity(RoleDTO dto) {
        SysRole entity = new SysRole();
        BeanUtil.copyProperties(dto, entity , false);
        return entity;
    }

    @Override
    public Boolean setResoucesByRoleId(Long roleId, List<Long> resourceIds) {
        if(null == roleId || null == resourceIds || resourceIds.isEmpty()){
            log.error("sharpknife===> 修改权限失败，参数信息为:roleId={},resourceIds={}",roleId,JSONUtil.toJsonStr(resourceIds));
            return false;
        }
        sysRoleResouceRelationMapper.delByRoleId(roleId);
        List<SysRoleResourceRelation> relations = new ArrayList<>();
        resourceIds.stream().forEach(resourceId->{
            SysRoleResourceRelation sysRoleResourceRelation = new SysRoleResourceRelation();
            sysRoleResourceRelation.setRoleId(roleId);
            sysRoleResourceRelation.setResourceId(resourceId);
            relations.add(sysRoleResourceRelation);
        });
        Integer count = sysRoleResouceRelationMapper.saveAll(relations);
        return count > 0;
    }
}
